package com.itheima.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.constant.MessageConstant;
import com.itheima.entity.Result;
import com.itheima.service.MemberService;
import com.itheima.service.ReportService;
import com.itheima.service.SetmealService;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.OutputStream;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

@RestController
@RequestMapping("/report")
public class ReportController {
    @Reference
    private ReportService reportService;
    @Reference
    private SetmealService setmealService;
    @Reference
    private MemberService memberService;
    /**
     * 会员折线图统计
     * @return
     */
    @RequestMapping("/getMemberReport")
    public Result getMemberReport(){
        Map map = new HashMap();
        List<String> months = new ArrayList<>();
        //获得日历对象，模拟时间就是当前时间
        Calendar calendar = Calendar.getInstance();
        //计算过去一年的12个月
        calendar.add(Calendar.MONTH,-12);
        for (int i = 0; i < 12; i++) {
            calendar.add(Calendar.MONTH,1);
            Date date = calendar.getTime();
            months.add(new SimpleDateFormat("yyyy.MM").format(date));
        }
        map.put("months",months);
        List<Integer> memberCount = memberService.findMemberCountByMonth(months);
        map.put("memberCount",memberCount);
        return new Result(true, MessageConstant.GET_MEMBER_NUMBER_REPORT_SUCCESS,map);
    }

    /**
     * 套餐饼状图统计
     * @return
     */
    @RequestMapping("/getSetmealReport")
    public Result getSetmealReport(){
        Map<String,Object> data = new HashMap();
        try {
            List<Map<String, Object>> setmealCount = setmealService.findSetmealCount();
            List<String> setmealNames = new ArrayList<>();
            for (Map<String, Object> map : setmealCount) {
                String name = (String) map.get("name");
                setmealNames.add(name);
            }
            data.put("setmealCount", setmealCount);
            data.put("setmealNames", setmealNames);
            return new Result(true, MessageConstant.GET_SETMEAL_COUNT_REPORT_SUCCESS, data);
        }catch (Exception e){
            e.printStackTrace();
            return new Result(false,MessageConstant.GET_SETMEAL_COUNT_REPORT_FAIL);
        }
    }

    /**
     * 营运数据统计
     * @return
     */
    @RequestMapping("/getBusinessReportData")
    public Result getBusinessReportData(){
      try {
          Map<String,Object> data = reportService.getBusinessReportData();
          return new Result(true,MessageConstant.GET_MEMBER_NUMBER_REPORT_SUCCESS,data);
      }catch (Exception e){
          return new Result(false,MessageConstant.GET_MEMBER_NUMBER_REPORT_FAIL);
      }
    }

    /**
     * excel导出
     * @return
     */
    @RequestMapping("/exportBusinessReport")
    public Result exportBusinessReport(HttpServletRequest request, HttpServletResponse response){
        try {
            //获取模板文件的绝对路径
            String filePath = request.getSession().getServletContext().getRealPath("template") + File.separator+"report_template.xlsx";
            //创建excel表对象
            Workbook workbook = new XSSFWorkbook(new FileInputStream(new File(filePath)));
            //获取第一个工作簿对象
            Sheet sheet = workbook.getSheetAt(0);
            //获取营运数据
            Map<String,Object> data = reportService.getBusinessReportData();
            //获取第三行对象
            Row row_3 = sheet.getRow(2);
            Cell row_3_Cell_6 = row_3.getCell(5);
            row_3_Cell_6.setCellValue((String) data.get("reportDate"));
            //获取第五行对象
            Row  row_5 = sheet.getRow(4);
            Cell row_5_Cell_6 = row_5.getCell(5);
            row_5_Cell_6.setCellValue((Integer)data.get("todayNewMember"));
            Cell row_5_Cell_8 = row_5.getCell(7);
            row_5_Cell_8.setCellValue((Integer)data.get("totalMember"));
            //获取第6行对象
            Row  row_6 = sheet.getRow(5);
            Cell row_6_Cell_6 = row_6.getCell(5);
            row_6_Cell_6.setCellValue((Integer)data.get("thisWeekNewMember"));
            Cell row_6_Cell_8 = row_6.getCell(7);
            row_6_Cell_8.setCellValue((Integer)data.get("thisMonthNewMember"));
            //获取第8行对象
            Row  row_8 = sheet.getRow(7);
            Cell row_8_Cell_6 = row_8.getCell(5);
            row_8_Cell_6.setCellValue((Integer)data.get("todayOrderNumber"));
            Cell row_8_Cell_8 = row_8.getCell(7);
            row_8_Cell_8.setCellValue((Integer)data.get("todayVisitsNumber"));
            //获取第9行对象
            Row  row_9 = sheet.getRow(8);
            Cell row_9_Cell_6 = row_9.getCell(5);
            row_9_Cell_6.setCellValue((Integer)data.get("thisWeekOrderNumber"));
            Cell row_9_Cell_8 = row_9.getCell(7);
            row_9_Cell_8.setCellValue((Integer)data.get("thisWeekVisitsNumber"));
            //获取第10行对象
            Row  row_10 = sheet.getRow(9);
            Cell row_10_Cell_6 = row_10.getCell(5);
            row_10_Cell_6.setCellValue((Integer)data.get("thisMonthOrderNumber"));
            Cell row_10_Cell_8 = row_10.getCell(7);
            row_10_Cell_8.setCellValue((Integer)data.get("thisMonthVisitsNumber"));
            //获取热门套餐对象
            List<Map<String,Object>> hotSetmeal = (List<Map<String, Object>>) data.get("hotSetmeal");
            int rowNum = 12;
            for(Map map : hotSetmeal){//热门套餐
                String name = (String) map.get("name");
                Long setmeal_count = (Long) map.get("setmeal_count");
                BigDecimal proportion = (BigDecimal) map.get("proportion");
                Row row = sheet.getRow(rowNum ++);
                row.getCell(4).setCellValue(name);//套餐名称
                row.getCell(5).setCellValue(setmeal_count);//预约数量
                row.getCell(6).setCellValue(proportion.doubleValue());//占比
            }
            //使用输出流进行表格下载,基于浏览器作为客户端下载
            OutputStream out = response.getOutputStream();
            response.setContentType("application/vnd.ms-excel");//代表的是Excel文件类型
            response.setHeader("content-Disposition", "attachment;filename=report.xlsx");//指定以附件形式进行下载
            workbook.write(out);

            out.flush();
            out.close();
            workbook.close();
            return null;
        }catch (Exception e){
            return new Result(false,MessageConstant.GET_BUSINESS_REPORT_FAIL);
        }
    }
}
